package main;

import java.awt.Button;
import java.awt.List;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JFrame;

public class Main {

	Stack stack;
	private JFrame frame;
	private TextField textFieldPush;
	private Button buttonPush;
	private TextField textFieldPop;
	private Button buttonPop;

	public static void main(String[] args) {
		Main window = new Main();
		window.frame.setVisible(true);
	}

	public Main() {
		stack = new Stack();

		frame = new JFrame();
		frame.setBounds(100, 100, 325, 325);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.getContentPane().setLayout(null);
		frame.setResizable(false);

		textFieldPush = new TextField();
		textFieldPush.setBounds(10, 10, 178, 22);
		frame.getContentPane().add(textFieldPush);

		buttonPush = new Button("Push");
		buttonPush.setBounds(194, 10, 115, 22);
		frame.getContentPane().add(buttonPush);

		final List stackList = new List();
		stackList.setBounds(10, 66, 299, 221);
		frame.getContentPane().add(stackList);

		textFieldPop = new TextField();
		textFieldPop.setBounds(10, 38, 178, 22);
		frame.getContentPane().add(textFieldPop);

		buttonPop = new Button("Pop");
		buttonPop.setBounds(194, 38, 115, 22);
		frame.getContentPane().add(buttonPop);

		buttonPush.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				stack.push(textFieldPush.getText());
				if (isNumeric(textFieldPush.getText()))
					stackList.add(textFieldPush.getText());
				else {
					stackList.add("\"" + textFieldPush.getText() + "\"");
				}
				textFieldPush.setText("");
				textFieldPush.requestFocus();
			}
		});

		buttonPop.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				if (!stack.empty()) {
					String str = (String) stack.pop();
					if (isNumeric(str))
						textFieldPop.setText(str);
					else
						textFieldPop.setText(str.substring(0, str.length()));
					textFieldPop.requestFocus();
					stackList.remove(stackList.getItemCount() - 1);
				} else {
					textFieldPop.setText("Error: Stack is empty");
				}
			}
		});
	}

	private boolean isNumeric(String str) {
		try {
			Double.parseDouble(str);
		} catch (NumberFormatException nfe) {
			return false;
		}
		return true;
	}
}
